/*
 * Copyright (C) 2011-2016 Markus Junginger, greenrobot (http://greenrobot.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.greenrobot.greendao.sample.slice;

import org.greenrobot.greendao.sample.DaoSession;
import org.greenrobot.greendao.sample.DaoMaster;
import org.greenrobot.greendao.sample.PeopleAdapter;
import org.greenrobot.greendao.sample.Person;
import org.greenrobot.greendao.sample.PersonDao;
import org.greenrobot.greendao.sample.PersonType;
import org.greenrobot.greendao.sample.ResourceTable;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.InputAttribute;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.TextField;
import ohos.app.Context;

import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.query.Join;
import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;

/**
 * PersonAbilitySlice
 */
public class PersonAbilitySlice extends AbilitySlice {
    private static final int TEXT_SIZE = 40;

    private static final int PADDING = 40;

    private Button addPersonButton;

    private Button joinButton;

    private PersonDao personDao;

    private PeopleAdapter peopleAdapter;

    private Query<Person> peopleQuery;

    private PeopleAdapter.PersonClickListener personClickListener = new PeopleAdapter.PersonClickListener() {
        @Override
        public void onPersonClick(int position) {
            Person person = peopleAdapter.getPerson(position);
            Long personDeleteId = person.getId();
            personDao.deleteByKey(personDeleteId);
            updatePeople();
        }
    };

    private TextField mName;

    private TextField mParent;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        initViewDynamically();

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "people-db");
        Database db = helper.getWritableDb();

        // get the person DAO
        DaoSession daoSession = new DaoMaster(db).newSession();

        personDao = daoSession.getPersonDao();

        // query all people, sorted a-z by their text
        peopleQuery = personDao.queryBuilder().orderAsc(PersonDao.Properties.NAME).build();
        updatePeople();
    }

    private void initView() {
        ComponentContainer rootLayout = (ComponentContainer) LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_main_ability_slice, null, false);
        addPersonButton = (Button) rootLayout.findComponentById(ResourceTable.Id_add_button);
        joinButton = (Button) rootLayout.findComponentById(ResourceTable.Id_join_button);
        mName = (TextField) rootLayout.findComponentById(ResourceTable.Id_add_text);
        mParent = (TextField) rootLayout.findComponentById(ResourceTable.Id_parent_text);
        ListContainer listContainer = (ListContainer) rootLayout.findComponentById(ResourceTable.Id_people_list);
        peopleAdapter = new PeopleAdapter(this, personClickListener);
        listContainer.setItemProvider(peopleAdapter);
        super.setUIContent(rootLayout);
    }

    private void initViewDynamically() {
        DirectionalLayout.LayoutConfig config = new DirectionalLayout.LayoutConfig(
            DirectionalLayout.LayoutConfig.MATCH_PARENT, DirectionalLayout.LayoutConfig.MATCH_PARENT);
        DirectionalLayout mainLayout = new DirectionalLayout(this);
        mainLayout.setLayoutConfig(config);
        mainLayout.setOrientation(Component.VERTICAL);

        TextField nameField = new TextField(this);
        nameField.setHint("Enter person name");
        nameField.setTextSize(TEXT_SIZE);
        nameField.setPadding(0, PADDING, 0, 0);
        mainLayout.addComponent(nameField);
        mName = nameField;

        TextField parentField = new TextField(this);
        parentField.setHint("Enter parent name");
        parentField.setTextSize(TEXT_SIZE);
        parentField.setPadding(0, PADDING, 0, 0);
        parentField.setTextInputType(InputAttribute.PATTERN_TEXT);
        mainLayout.addComponent(parentField);
        mParent = parentField;

        Button addButton = new Button(this);
        addButton.setText("Add");
        addButton.setTextSize(TEXT_SIZE);
        addButton.setPadding(0, PADDING, 0, 0);
        addButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                addPerson();
            }
        });
        mainLayout.addComponent(addButton);

        Button joinChildButton = new Button(this);
        joinChildButton.setText("Adams children (Join)");
        joinChildButton.setTextSize(TEXT_SIZE);
        joinChildButton.setPadding(0, PADDING, 0, 0);
        joinChildButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                join();
            }
        });
        mainLayout.addComponent(joinChildButton);

        ListContainer personList = new ListContainer(this);
        personList.setLayoutConfig(new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT,
            ComponentContainer.LayoutConfig.MATCH_CONTENT));
        peopleAdapter = new PeopleAdapter(this, personClickListener);
        personList.setItemProvider(peopleAdapter);
        mainLayout.addComponent(personList);

        super.setUIContent(mainLayout);
    }

    private void updatePeople() {
        List<Person> peopleList = peopleQuery.list();
        peopleAdapter.setPeople(peopleList);
    }

    private void addPerson() {
        final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        String comment = "Added on " + df.format(new Date());

        Person person = new Person();
        person.setName(mName.getText());
        person.setComment(comment);
        person.setParent(mParent.getText());
        person.setDate(new Date());
        person.setType(PersonType.NORMAL);
        personDao.insert(person);
        updatePeople();

        mName.setText("");
        mParent.setText("");
    }

    private void join() {
        QueryBuilder<Person> qb = personDao.queryBuilder();
        Join parent = qb.join(Person.class, PersonDao.Properties.ID);
        Join grandfather = qb.join(parent, PersonDao.Properties.ID, Person.class, PersonDao.Properties.ID);
        grandfather.where(PersonDao.Properties.PARENT.eq("adam"));
        List<Person> peopleList = qb.list();
        peopleAdapter.setPeople(peopleList);
    }

    /**
     * Custom Open helpers
     */
    public static class ExampleOpenHelper extends DaoMaster.OpenHelper {
        /**
         * Constructor for ExampleOpenHelper
         * @param context context
         * @param name name of the db
         */
        public ExampleOpenHelper(Context context, String name) {
            super(context, name);
        }

        @Override
        public void onCreate(Database db) {
            super.onCreate(db);

            // Insert some example data.
            // INSERT INTO NOTE (_id, DATE, TEXT) VALUES(1, 0, 'Example Note')
            db.execSQL("INSERT INTO " + PersonDao.TABLENAME + " (" +
                    PersonDao.Properties.ID.columnName + ", " +
                    PersonDao.Properties.DATE.columnName + ", " +
                    PersonDao.Properties.NAME.columnName +
                    ") VALUES(1, 0, 'Example Note')");
        }
    }

}